package course.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import course.pojo.entity.College;
import course.pojo.entity.Student;
import course.pojo.entity.Zhuanye;
import course.pojo.vo.Page;
import course.pojo.vo.StudentRespVo;
import course.service.CollegeService;
import course.service.StudentService;
import course.service.ZhuanyeService;
import course.service.impl.CollegeServiceImpl;
import course.service.impl.StudentServiceImpl;
import course.service.impl.ZhuanyeServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/2 14:24
 */
@WebServlet("/admin/studentController")
public class StudentController extends BaseController {
    private StudentService studentService = new StudentServiceImpl();
    private ZhuanyeService zhuanyeService = new ZhuanyeServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();

    /**
     * 跳转到添加模态框
     *
     * @Version 3.0
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*List<Zhuanye> list = zhuanyeService.getList();
        req.setAttribute("list", list);*/

        List<College> collegeList = collegeService.getList();
        req.setAttribute("list", collegeList);

        req.getRequestDispatcher("/student_add.jsp").forward(req, resp);
    }

    /**
     * 跳转到修改模态框
     */
    protected void updatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*List<Zhuanye> list = zhuanyeService.getList();
        req.setAttribute("list", list);*/

        String zid = req.getParameter("zid");
        Zhuanye zhuanye = zhuanyeService.getById(Integer.valueOf(zid));
        Integer cid = zhuanye.getCid();
        req.setAttribute("cid", cid);

        List<College> collegeList = collegeService.getList();
        req.setAttribute("list", collegeList);

        req.getRequestDispatcher("/student_update.jsp").forward(req, resp);
    }

    /**
     * 根据cid获取所有zhuanye，响应json给前端
     */
    protected void colleges(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        String cid = req.getParameter("cid");
        List<Zhuanye> list = zhuanyeService.getListByCid(Integer.valueOf(cid));

        PrintWriter writer = resp.getWriter();
        writer.println(new ObjectMapper().writeValueAsString(list));
    }

    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        this.main(req, resp, pageNo);
    }

    /**
     * 传递分页参数进行分页
     */
    protected void main(HttpServletRequest req, HttpServletResponse resp, String pageNo) throws ServletException, IOException {
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Student> page = studentService.page(Integer.valueOf(pageNo));
        List<Student> studentList = page.getList();
        List<StudentRespVo> respVos = studentList.stream().map(student -> {
            try {
                StudentRespVo respVo = new StudentRespVo();
                BeanUtils.copyProperties(respVo, student);
                //设置专业名和学院名,学院id
                Zhuanye zhuanye = zhuanyeService.getById(student.getZid());
                respVo.setZname(zhuanye.getZname());
                College college = collegeService.getById(zhuanye.getCid());
                respVo.setCname(college.getCname());
                respVo.setCid(collegeService.getById(zhuanye.getCid()).getCid());

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Page<StudentRespVo> voPage = new Page<>();
        try {
            BeanUtils.copyProperties(voPage, page);
            voPage.setList(respVos);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.setAttribute("page", voPage);
        req.getRequestDispatcher("/student_manage.jsp").forward(req, resp);
    }

    /**
     * 添加学生
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        String sname = req.getParameter("sname");
        String ssex = req.getParameter("ssex");
        String zid = req.getParameter("zid");

        String total = req.getParameter("total");//获取总数量
        String pages = req.getParameter("pages");//获取总页码数

        Integer pageSize = new Page<>().getPageSize();

        Integer pages2 = Integer.valueOf(pages);
        if (Integer.parseInt(total) % pageSize == 0) {
            pages2 += 1;
        }

        Student student = new Student(Integer.valueOf(sid), sname, ssex, Integer.valueOf(zid));
        int i = studentService.addStudent(student);
        if (i > 0) {
            this.main(req, resp, String.valueOf(pages2));
        }
    }

    /**
     * 删除学生
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        String pn = req.getParameter("pn");

        int i = studentService.deleteById(Integer.valueOf(sid));
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 批量删除所有选中学生
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        List<String> list = Arrays.asList(ids);
        List<Integer> integers = list.stream().map(Integer::valueOf).collect(Collectors.toList());

        int i = studentService.deleteSelect(integers);
        if (i > 0) {
            this.index(req, resp);
        }
    }

    /**
     * 通过sid获取student对象
     */
    protected void getStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String sid = req.getParameter("sid");

        Student student = studentService.getById(Integer.valueOf(sid));
        Zhuanye zhuanye = zhuanyeService.getById(student.getZid());

        StudentRespVo studentRespVo = new StudentRespVo();
        try {
            BeanUtils.copyProperties(studentRespVo, student);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //设置专业名称和学院名称，学院id
        studentRespVo.setZname(zhuanye.getZname());
        studentRespVo.setCname(collegeService.getById(zhuanye.getCid()).getCname());
        studentRespVo.setCid(collegeService.getById(zhuanye.getCid()).getCid());

        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(studentRespVo);
        PrintWriter writer = resp.getWriter();
        writer.write(jsonString); //将json对象响应给前端
        writer.flush();
    }

    /**
     * 修改学生
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        String sname = req.getParameter("sname");
        String ssex = req.getParameter("ssex");
        String zid = req.getParameter("zid");
        String pn = req.getParameter("pn");

        Student student = new Student(Integer.valueOf(sid), sname, ssex, Integer.valueOf(zid));

        int i = studentService.updateById(student);
        if (i > 0) {
            this.main(req, resp, pn);
        }
    }

    /**
     * 查询所有学生数量
     */
    protected void count(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        long count = studentService.count();
        PrintWriter writer = resp.getWriter();
        writer.println(count);
        writer.flush();
    }

    /**
     * 根据学生名查询学生信息
     */

    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String sname = req.getParameter("sname");

        String pageNo = req.getParameter("pageNo");
        if (pageNo == null || Integer.parseInt(pageNo) <= 0) {
            pageNo = "1";
        }

        Page<Student> page = studentService.query(sname, Integer.valueOf(pageNo));

        List<Student> studentList = page.getList();
        List<StudentRespVo> respVos = studentList.stream().map(student -> {
            try {
                StudentRespVo respVo = new StudentRespVo();
                BeanUtils.copyProperties(respVo, student);
                //设置专业名和学院名
                Zhuanye zhuanye = zhuanyeService.getById(student.getZid());
                respVo.setZname(zhuanye.getZname());
                College college = collegeService.getById(zhuanye.getCid());
                respVo.setCname(college.getCname());

                return respVo;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Page<StudentRespVo> voPage = new Page<>();
        try {
            //属性对拷
            BeanUtils.copyProperties(voPage, page);
            voPage.setList(respVos);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.setAttribute("sname", sname);
        req.setAttribute("page", voPage);
        req.getRequestDispatcher("/student_manage.jsp").forward(req, resp);
    }
}
